const { ClientIdCredential } = require('@agconnect/common-server/dist/credential-service/clientid-credential');
import * as cloudDb from '@agconnect/database-server';
import * as agc from '@agconnect/common-server';

const ZONE_NAME = "HarmonyOSDeveloper";

export const getCredential = (context, logger) => {
  try {
    const credential = JSON.parse(context.env.PROJECT_CREDENTIAL);
    if (credential.type === 'team_client_id') {
      return new ClientIdCredential('', '', credential.developer_id, credential.type, credential.client_id, credential.client_secret, credential.configuration_version);
    } else if (credential.type === 'project_client_id') {
      return new ClientIdCredential(credential.project_id, credential.region, credential.developer_id, credential.type, credential.client_id, credential.client_secret, credential.configuration_version);
    }
  } catch {
    logger.error('get project credential failed');
  }
}

export const initCloudDb = (credential, logger) => {

  try {
    // 初始化AGCClient
    logger.info("begin to init agcClient");
    let agcClient;
    let cloudDb;
    try {
      agcClient = agc.AGCClient.getInstance();
    } catch {
      agc.AGCClient.initialize(credential);
      agcClient = agc.AGCClient.getInstance();
    }
    // 初始化AGConnectCloudDB实例
    logger.info("begin to init cloudDb");
    let cloudDbInstance;
    try {
      cloudDbInstance = cloudDb.AGConnectCloudDB.getInstance(agcClient);
    } catch {
      cloudDb.AGConnectCloudDB.initialize(agcClient);
      cloudDbInstance = cloudDb.AGConnectCloudDB.getInstance(agcClient);
    }
    // 创建CloudDBZoneConfig配置对象，并设置云侧CloudDB zone名称，打开Cloud DB zone实例
    const cloudDBZoneConfig = new cloudDb.CloudDBZoneConfig(ZONE_NAME);
    return cloudDbInstance.openCloudDBZone(cloudDBZoneConfig);
  } catch (err) {
    logger.error("init CloudDBZoneWrapper error: " + err);
  }
}